package com.hzncc.flowable_diboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzncc.flowable_diboot.vo.ProductSortMenuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.diboot.core.service.impl.BaseServiceImpl;

import com.hzncc.flowable_diboot.entity.ProductSort;
import com.hzncc.flowable_diboot.mapper.ProductSortMapper;
import com.hzncc.flowable_diboot.service.ProductSortService;

import java.util.ArrayList;
import java.util.List;


/**
* 产品分类 相关Service实现类
* @author MyName
* @version 1.0
* @date 2024-07-04
* Copyright © MyCorp
*/
@Slf4j
@Service
public class ProductSortServiceImpl extends BaseServiceImpl<ProductSortMapper, ProductSort> implements ProductSortService {
    @Autowired
    private ProductSortMapper productSortMapper;


    @Override
    public List<ProductSortMenuVO> getTree(String category) {
        QueryWrapper<ProductSort> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category",category);
        List<ProductSort> allProductSort = productSortMapper.selectList(queryWrapper);

        List<ProductSortMenuVO> menus = new ArrayList<>();
        for ( ProductSort productSort : allProductSort ){
            ProductSortMenuVO productSortMenuVO = new ProductSortMenuVO();
            productSortMenuVO.setId(productSort.getId());
            productSortMenuVO.setName(productSort.getName());
            productSortMenuVO.setPid(productSort.getPid());
            productSortMenuVO.setCategory(productSort.getCategory());
            if ( productSort.getPid().equals("0") ){
                menus.add(productSortMenuVO);
            }
        }

        for (ProductSortMenuVO productSortMenuVO : menus){
            List<ProductSortMenuVO> child = getChild(productSortMenuVO.getId(), allProductSort);
            productSortMenuVO.setSortMenu(child);
        }

        return menus;
    }


    private List<ProductSortMenuVO> getChild(String id,List<ProductSort> allProductSort){
        List<ProductSortMenuVO> childList = new ArrayList<>();
        for ( ProductSort productSort : allProductSort ){
            ProductSortMenuVO productSortMenuVO = new ProductSortMenuVO();
            productSortMenuVO.setId(productSort.getId());
            productSortMenuVO.setName(productSort.getName());
            productSortMenuVO.setPid(productSort.getPid());
            productSortMenuVO.setCategory(productSort.getCategory());
            if ( productSort.getPid().equals(id) ){
                childList.add(productSortMenuVO);
            }
        }

        for (ProductSortMenuVO productSortMenuVO:childList){
            List<ProductSortMenuVO> child = getChild(productSortMenuVO.getId(),allProductSort);
            productSortMenuVO.setSortMenu(child);
        }

        if( childList.size() == 0 ){
            return null;
        }

        return childList;
    }


}